//
//
//  PrinterHelper.m
//  ICrEAM
//
//  Created by mac on 16/9/21.
//  Copyright © 2016年 Yonyou. All rights reserved.
//
#import "PrinterHelper.h"

@implementation PrinterHelper

- (id)initWithPrintView:(UIView *)printView andpage:(NSInteger)page
{
    if ( self = [super init] )
    {
        if (page) {
            _page=page;
        }else{
            _page=1;
        }
        _printView = printView;
        
        [self print];
    }
    
    return self;
}

//截取原图  截取部分 打印的图片就是从这里来
- (UIImage *)imageFromImage:(UIImage *)image {
    
    
    UIGraphicsBeginImageContext(CGSizeMake(2100, 2970));
    
    [image drawInRect:CGRectMake(0, 0, 2100, 2970)];
    
    
    UIImage *resultImg=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImg;
    
}


-(UIImage *)scaleImge:(UIImage *)image{
    UIImage *orginImage=[self imageFromImage:[UIImage imageNamed:@"pring_bg"]];
    
    
    
    UIGraphicsBeginImageContextWithOptions(orginImage.size, NO, 0);
    //    [orginImage drawInRect:CGRectMake(0, 0, 595, 842)];
    [image drawAtPoint:CGPointMake(20, 40)];
    
    UIImage *resultImg=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImg;
    
}
/*
 - (void)print1
 {
 UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
 
 if(!print)
 {
 
 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
 [alert show];
 [alert release];
 //        return NO;
 }
 
 
 CGSize pageSize = print.printPaper.paperSize;
 pageSize = CGSizeMake(print.printFormatter.printPageRenderer.printableRect.size.width, print.printFormatter.printPageRenderer.printableRect.size.height);
 
 NSData *screenImgData = nil;
 {//截屏
 UIGraphicsBeginImageContext(_printView.bounds.size);
 [_printView.layer renderInContext:UIGraphicsGetCurrentContext()];
 
 UIImage *imageContext= UIGraphicsGetImageFromCurrentImageContext();
 
 UIGraphicsEndImageContext();
 UIImage *image=[self scaleImge:imageContext];
 screenImgData = [UIImageJPEGRepresentation(image, 1) retain];
 }
 }
 */

- (void)print
{
    UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];
    
    if(!print)
    {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        //        return NO;
    }
    
    
    CGSize pageSize = print.printPaper.paperSize;
    pageSize = CGSizeMake(print.printFormatter.printPageRenderer.printableRect.size.width, print.printFormatter.printPageRenderer.printableRect.size.height);
    
    //    NSData *screenImgData = nil;
    //截屏
    UIGraphicsBeginImageContext(_printView.bounds.size);
    [_printView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *imageContext= UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    CGFloat height=imageContext.size.height*2100.0/imageContext.size.width;
    NSMutableArray *alldata=[NSMutableArray array];
    
    if (height<2900.) {
        UIImage *image=[self scaleImge:imageContext];
        NSData   *screenImgData =UIImageJPEGRepresentation(image, 1) ;
        [alldata addObject:screenImgData];
    }else{
    for (CGFloat x=0;x<height-80; x+=2970-80) {
        CGImageRef imageRef1 = CGImageCreateWithImageInRect([imageContext CGImage], CGRectMake(0, x, imageContext.size.width, 2970-80));
        UIImage *image1 = [UIImage imageWithCGImage:imageRef1];
         UIImage *image=[self scaleImge:image1];
        CGImageRelease(imageRef1);
        NSData  *screenImgData =UIImageJPEGRepresentation(image, 1);
        [alldata addObject:screenImgData];
    }
    
    }
    
    
    //    UIImage *resultImage;
    //    {//webview
    //        int webViewHeight = [[webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
    //        int scrollByY = webview.frame.size.height;
    //        int imageName = 0;
    //
    //        [webview stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];
    //
    //        NSMutableArray* images = [[NSMutableArray alloc] init];
    //
    //        CGRect screenRect = webview.frame;
    //        double currentWebViewHeight = webViewHeight;
    //        while (currentWebViewHeight > 0)
    //        {
    //            imageName ++;
    //
    //            UIGraphicsBeginImageContext(screenRect.size);
    //            CGContextRef ctx = UIGraphicsGetCurrentContext();
    //            [[UIColor blackColor] set];
    //            CGContextFillRect(ctx, screenRect);
    //
    //            [webview.layer renderInContext:ctx];
    //
    //            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //            UIGraphicsEndImageContext();
    //
    //            if(currentWebViewHeight < scrollByY)
    //            {
    //                CGRect lastImageRect = CGRectMake(0, scrollByY - currentWebViewHeight, webview.frame.size.width, currentWebViewHeight);
    //                CGImageRef imageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
    //
    //                newImage = [UIImage imageWithCGImage:imageRef];
    //                CGImageRelease(imageRef);
    //            }
    //            [images addObject:newImage];
    //
    //            [webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollBy(0,%d);", scrollByY]];
    //            currentWebViewHeight -= scrollByY;
    //        }
    //
    //        [webview stringByEvaluatingJavaScriptFromString:@"window.scrollTo(0,0);"];
    //
    ////        UIImage *resultImage;
    //
    //        if(images.count > 1) {
    //            //join all images together..
    //            CGSize sz;
    //            for(int i=0;i<images.count;i++) {
    //
    //                sz.width = MAX(sz.width, ((UIImage*)[images objectAtIndex:i]).size.width );
    //                sz.height += ((UIImage*)[images objectAtIndex:i]).size.height;
    //            }
    //
    //            UIGraphicsBeginImageContext(sz);
    //            CGContextRef ctx = UIGraphicsGetCurrentContext();
    //            [[UIColor blackColor] set];
    //            CGContextFillRect(ctx, screenRect);
    //
    //            int y=0;
    //            for(int i=0;i<images.count;i++) {
    //
    //                UIImage* img = [images objectAtIndex:i];
    //                [img drawAtPoint:CGPointMake(0,y)];
    //                y += img.size.height;
    //            }
    //
    //            resultImage = UIGraphicsGetImageFromCurrentImageContext();
    //            UIGraphicsEndImageContext();
    //        } else {
    //
    //            resultImage = [images objectAtIndex:0];
    //        }
    //    }
    
    //NSData *finalImageData = UIImageJPEGRepresentation([UIImage imageNamed:@"111.jpg"], 0.1f);
    //    NSData *finalImageData = UIImageJPEGRepresentation(resultImage, 0.1f);
    
    
    //    print.delegate = self;
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGrayscale;
    //    printInfo.jobName = [[(PageView *)[self view] representedPage] title];
    printInfo.jobName = @"111";
    printInfo.duplex = UIPrintInfoDuplexShortEdge;
    printInfo.orientation=UIPrintInfoOrientationPortrait;
    print.printInfo = printInfo;
    print.showsPageRange = YES;
    
    print.showsNumberOfCopies=NO;
    //    print.printingItem = screenImgData;
    NSMutableArray *arr=[NSMutableArray array];
    for (int i=0; i<_page; i++) {
        [arr addObjectsFromArray:alldata];
    }
    print.printingItems=arr;
    //    UIViewPrintFormatter *viewFormatter = [_printView viewPrintFormatter];
    //    viewFormatter.startPage = 0;
    //    print.printFormatter = viewFormatter;
    
    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
        
        
        if(!completed && error){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Print Unavailable!" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
   
        }
        
        
    };
    
    [print presentAnimated:YES completionHandler:completionHandler];
}


@end
